package com.nami.gate.router.register.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;

import com.nami.gate.router.register.RegisterService;
import com.nami.gate.router.register.request.RegisterRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

import static com.nami.gate.router.constants.RegisterConst.SERVICE_NAME;
import static com.nami.gate.router.constants.RegisterConst.SERVICE_NAME_SPACE_PROD;


public class NacosRegisterServiceImpl implements RegisterService {

    private static final Logger log = LoggerFactory.getLogger(NacosRegisterServiceImpl.class);

    private NamingService namingService;

    @Override
    public boolean start(RegisterRequest request) throws Exception {

        Properties properties = new Properties();
        properties.put("serverAddr", request.getServerAddr());
        properties.put("namespace", request.getNamespace());
        properties.put("username", request.getUsername());
        properties.put("password", request.getPassword());
        namingService = NacosFactory.createNamingService(properties);

//        NamingService namingService = NacosFactory.createNamingService(request.getRegisterAddr());

        Instance instance = new Instance();
        instance.setIp(request.getIp()); // 实例IP
        instance.setPort(request.getPort()); // 实例端口
        instance.setWeight(1.0); // 实例权重
        instance.setHealthy(true); // 实例健康状态
        instance.setEnabled(true); // 实例启用状态
        instance.setEphemeral(true);
        instance.setInstanceId(UUID.fastUUID().toString()); // 实例ID
        namingService.registerInstance(SERVICE_NAME, SERVICE_NAME_SPACE_PROD, instance);

        log.info("[nacos-client] register [{}] success.", request.getServerAddr());
        return true;
    }

    @Override
    public void shutdown() {
        try {
            namingService.shutDown();
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

}
